from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QLineEdit
from PyQt5.QtCore import QThread, pyqtSignal
from VideoSplitter import VideoSplitter
from J_ui import *
import sys
import traceback
from functools import partial
from ConfigManager import ConfigManager
import os


class VideoExportThread(QThread):
    """导出视频子线程"""
    # 对外输出信号
    output_signal = pyqtSignal(str)

    def __init__(self, drafts_path, drafts_name, output_directory, other_source_video):
        super().__init__()
        self.drafts_path = drafts_path
        self.drafts_name = drafts_name
        self.output_directory = output_directory
        self.other_source_video = other_source_video

    def run(self):
        def print_to_signal(text):
            self.output_signal.emit(text)

        try:
            vs = VideoSplitter(self.drafts_path, self.drafts_name, self.output_directory, self.other_source_video,
                               callback=print_to_signal)
            vs.split_video()
        except Exception as e:
            tb_str = traceback.format_exception(type(e), e, e.__traceback__)
            self.output_signal.emit(f"发生异常：{str(e)}\n\n回溯信息：\n{''.join(tb_str)}")


class MyWindow(QMainWindow):
    """程序主线程"""

    def __init__(self):
        super().__init__()

        self.video_export_thread = None

        # 固定创建UI类的实例并设置UI-------------------------------------------------
        self.ui = Ui_JianYing()
        self.ui.setupUi(self)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # 隐藏边框
        # 固定创建UI类的实例并设置UI-------------------------------------------------

        # 读取配置文件写到输入框
        config_file = self.get_config_file_path()
        self.config_manager = ConfigManager(config_file)
        self.ui.drafs_path_input.setText(self.config_manager.get_key('d_path'))
        self.ui.drafs_name_input.setText(self.config_manager.get_key('d_name'))
        self.ui.out_dir_input.setText(self.config_manager.get_key('out_dir'))
        self.ui.other_video_input.setText(self.config_manager.get_key('other_video_name'))

        # 连接按钮点击事件到槽函数
        self.ui.start_output_btn.clicked.connect(self.start_processing)

        # 选择路径按钮连接到槽函数
        self.ui.drafs_path_input_btn.clicked.connect(partial(self.select_dir, self.ui.drafs_path_input))
        self.ui.drafs_name_input_btn.clicked.connect(partial(self.select_dir, self.ui.drafs_name_input))
        self.ui.out_dir_input_btn.clicked.connect(partial(self.select_dir, self.ui.out_dir_input))
        self.ui.other_video_btn.clicked.connect(partial(self.select_file, self.ui.other_video_input))

        # 检查选择框的变化
        if self.ui.default_check.isChecked():
            self.set_all_widgets_in_layout(self.ui.horizontalLayout_6, show=False)
        self.ui.buttonGroup.buttonClicked.connect(self.checkbox_state_changed)

        # 运行实例
        self.show()

    def select_dir(self, input_widgets: QLineEdit):
        """选择单个目录"""
        options = QFileDialog.Options()
        file_dialog = QFileDialog(self)
        file_dialog.setOptions(options)
        file_dialog.setFileMode(QFileDialog.Directory)
        if file_dialog.exec_():
            selected_path = file_dialog.selectedFiles()[0]
            input_widgets.setText(selected_path)

    def select_file(self, input_widgets: QLineEdit):
        """选择单个文件"""
        options = QFileDialog.Options()
        file_dialog = QFileDialog(self)
        file_dialog.setOptions(options)
        file_dialog.setFileMode(QFileDialog.ExistingFile)
        if file_dialog.exec_():
            selected_path = file_dialog.selectedFiles()[0]
            input_widgets.setText(selected_path)

    def start_processing(self):
        # 清除之前的输出
        self.ui.log_out.clear()

        # 获取QLineEdit上的内容
        d_path = self.ui.drafs_path_input.text()
        out_dir = self.ui.out_dir_input.text()
        d_name = self.ui.drafs_name_input.text()
        other_video_name = self.ui.other_video_input.text() if self.ui.other_check.isChecked() else ''

        # 判断三个值是否为空
        if not d_path or not out_dir or not d_name:
            self.ui.log_out.append("请确保输入框中的内容都不为空！")
            return
        if self.ui.other_check.isChecked() and not self.ui.other_video_input.text().strip():
            self.ui.log_out.append("当选择 '指定其他视频' 时, 请选择视频源！")
            return

        # 保存配置到文件
        self.config_manager.set_key('d_path', d_path)
        self.config_manager.set_key('out_dir', out_dir)
        self.config_manager.set_key('d_name', d_name)
        self.config_manager.set_key('other_video_name', other_video_name if other_video_name else '')

        # 创建子线程
        self.video_export_thread = VideoExportThread(drafts_path=d_path,
                                                     drafts_name=d_name,
                                                     output_directory=out_dir,
                                                     other_source_video=other_video_name)
        # 设置线程信号连接槽函数
        self.video_export_thread.output_signal.connect(self.update_output)
        # 启动子线程
        self.video_export_thread.start()

    def update_output(self, text):
        self.ui.log_out.append(text)

    @staticmethod
    def get_config_file_path():
        """获取用户home目录, 作为配置文件存放路径"""
        user_home = os.path.expanduser("~")
        file_path = os.path.join(user_home, "config.ini")

        return file_path

    @staticmethod
    def set_all_widgets_in_layout(layout, show=False):
        for i in range(layout.count()):
            item = layout.itemAt(i)
            if item.widget():
                item.widget().setHidden(not show)

    def checkbox_state_changed(self):
        if self.ui.default_check.isChecked():
            self.set_all_widgets_in_layout(self.ui.horizontalLayout_6, show=False)
        elif self.ui.other_check.isChecked():
            self.set_all_widgets_in_layout(self.ui.horizontalLayout_6, show=True)

    @staticmethod
    def checkbox_clicked(button_group):
        for checkbox_id in range(button_group.buttons().count()):
            checkbox = button_group.button(checkbox_id)
            if checkbox.isChecked():
                print(f"{checkbox.text()}复选框被选中")

    # 固定, 不可更改-------------------------------------------------------------
    def mousePressEvent(self, event):
        """重写鼠标点击事件"""
        if event.button() == QtCore.Qt.LeftButton:
            # 鼠标按下时设置为移动状态
            self.Move = True
            # 记录起始点坐标
            self.Point = event.globalPos() - self.pos()
            event.accept()

    def mouseMoveEvent(self, QMouseEvent):
        """移动时间"""
        # 切记这里的条件不能写死，只要判断move和鼠标执行即可！
        if QtCore.Qt.LeftButton and self.Move:
            # 移动到鼠标到达的坐标点！
            self.move(QMouseEvent.globalPos() - self.Point)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        """结束事件"""
        self.Move = False
    # 固定, 不可更改-------------------------------------------------------------


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MyWindow()
    sys.exit(app.exec_())
